package com.pipe.connector.nettyhandler;

import com.pipe.connector.RowDataListener;
import com.pipe.connector.actor.SessionStatusActor;
import com.pipe.protocol.BasePackage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Kiven
 */
public class BasePackageDecoder extends ByteToMessageDecoder {
    private static Logger LOG = LoggerFactory.getLogger(BasePackageDecoder.class);

    private SessionStatusActor actor;

    public BasePackageDecoder(String databaseName, String userName, String password, int binlogPos, String binlogFile, RowDataListener listener) {
        this.actor = new SessionStatusActor(databaseName, userName, password, binlogPos, binlogFile, listener);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) {
        try {
            BasePackage basePackage = BasePackage.getBasePackage(byteBuf);
            if (basePackage == null){
                LOG.info("[BasePackage] not enough data!");
                return;
            }
            actor.handler(basePackage, ctx);
        } catch (Exception e){
            ctx.fireExceptionCaught(e);
        }
    }
}